<?php

namespace app\agent\controller;

use app\common\controller\CommonService;
use think\Controller;
use think\Db;
use think\exception\DbException;
use think\facade\Validate;
use think\Request;

class CodeManage extends Controller
{

    /**
     * 激活码列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function activateCodeList(Request $request)
    {
        $agentId = $request->agentId;
        $data['unuseCodeList'] = Db::name('agent_code')->field('id,code_no,code_duration')->where('code_type', 1)->where('agent_id', $agentId)->where('is_use', 0)->select();
        $useCodeList = Db::name('agent_code')->field('id,code_no,code_duration,use_partner_id,use_time,binding_time')->where('code_type', 1)->where('agent_id', $agentId)->where('is_use', 1)->select();
        $data['useCodeList'] = [];
        foreach ($useCodeList as $k => $v) {
            $item['id'] = $v['id'];
            $item['code_no'] = $v['code_no'];
            $item['code_duration'] = $v['code_duration'];
            $item['use_time'] = $v['use_time'];
            $item['binding_time'] = $v['binding_time'];
            $partner = Db::name('super_partner')->find($v['use_partner_id']);
            $item['status'] = $partner['status'];
            $item['expire_time'] = $partner['expire_time'];
            $user = Db::name('user_manage')->find($partner['uid']);
            $item['nickname'] = CommonService::emoji_decode($user['nickname']);
            $item['headimgurl'] = $user['headimgurl'];
            $item['tel'] = $user['tel'];
            $data['useCodeList'][] = $item;
            unset($item);
        }
        return CommonService::success($data);
    }


    /**
     *
     *  续费码列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function renewCodeList(Request $request)
    {
        $agentId = $request->agentId;
        $data['unuseCodeList'] = Db::name('agent_code')->field('id,code_no,code_duration')->where('code_type', 2)->where('agent_id', $agentId)->where('is_use', 0)->select();
        $useCodeList = Db::name('agent_code')->field('id,code_no,code_duration,use_partner_id,use_time,binding_time')->where('code_type', 2)->where('agent_id', $agentId)->where('is_use', 1)->select();
        $data['useCodeList'] = [];
        foreach ($useCodeList as $k => $v) {
            $item['id'] = $v['id'];
            $item['code_no'] = $v['code_no'];
            $item['code_duration'] = $v['code_duration'];
            $item['use_time'] = $v['use_time'];
            $item['binding_time'] = $v['binding_time'];
            $partner = Db::name('super_partner')->find($v['use_partner_id']);
            $item['status'] = $partner['status'];
            $item['expire_time'] = $partner['expire_time'];
            $user = Db::name('user_manage')->find($partner['uid']);
            $item['nickname'] = CommonService::emoji_decode($user['nickname']);
            $item['headimgurl'] = $user['headimgurl'];
            $item['tel'] = $user['tel'];
            $data['useCodeList'][] = $item;
            unset($item);
        }
        return CommonService::success($data);
    }


    /**
     * 通过手机号查询用户昵称电话
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfoByTel(Request $request)
    {
        $requestData = request()->post();
        $validate = Validate::make([
            'tel|手机号' => 'require|mobile',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $user = Db::name('user_manage')->where('tel', $requestData['tel'])->find();
        if (empty($user)) {
            return CommonService::error(6);
        }
        $data['nickname'] = CommonService::emoji_decode($user['nickname']);
        $data['tel'] = CommonService::emoji_decode($user['tel']);
        return CommonService::success($data);
    }


    /**
     * 代理商绑定合伙人
     * @param Request $request
     * @return \think\response\Json
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function activateCodeBinding(Request $request)
    {
        $agentId = $request->agentId;
        $requestData = request()->post();
        $validate = Validate::make([
            'id' => 'require|>:0',
            'tel' => 'require|mobile',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $code = Db::name('agent_code')->where('agent_id', $agentId)->where('code_type', 1)->where('id', $requestData['id'])->find();
        if (empty($code)) {
            return CommonService::error(7);
        }
        if($code['is_use'] == 1){
            return CommonService::error(9);
        }
        $user = Db::name('user_manage')->where('tel', $requestData['tel'])->find();
        if (empty($user)) {
            return CommonService::error(1);
        }
        $partner = Db::name('super_partner')->where('uid', $user['id'])->find();
        if ($partner) {
            return CommonService::error(8);
        }

        Db::transaction(function () use ($user, $code) {
            $id = Db::name('super_partner')->insertGetId([
                'uid' => $user['id'],
                'user_one_rebate_percent' => 14,
                'user_two_rebate_percent' => 0,
                'status' => 2,
                'expire_time' => strtotime('+' . $code['code_duration'] . " month"),
            ]);
            Db::name('agent_code')->where('id', $code['id'])->update(['is_use' => 1, 'binding_time' => time(), 'use_partner_id' => $id]);
        });
        return CommonService::success([], '绑定成功！');
    }


    /**
     * 代理商续费合伙人
     * @param Request $request
     * @return \think\response\Json
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function renewCodeUse(Request $request)
    {
        $agentId = $request->agentId;
        $requestData = request()->post();
        $validate = Validate::make([
            'id' => 'require|>:0',
            'tel' => 'require|mobile',
        ]);
        if (!$validate->check($requestData)) {
            return CommonService::error($validate->getError());
        }
        $code = Db::name('agent_code')->where('agent_id', $agentId)->where('code_type', 2)->where('id', $requestData['id'])->find();
        if (empty($code)) {
            return CommonService::error(7);
        }
        if($code['is_use'] == 1){
            return CommonService::error(9);
        }

        $user = Db::name('user_manage')->where('tel', $requestData['tel'])->find();
        if (empty($user)) {
            return CommonService::error(1);
        }
        $partner = Db::name('super_partner')->where('uid', $user['id'])->find();
        if (!$partner) {
            return CommonService::error(1);
        }
        Db::transaction(function () use ($user, $code, $partner) {
            $expireTime = $partner['expire_time'] > time() ? $partner['expire_time'] : time();
            Db::name('super_partner')->where('id', $partner['id'])->update([
                'expire_time' => strtotime('+' . $code['code_duration'] . " month", $expireTime),
            ]);

            Db::name('agent_code')->where('id', $code['id'])->update(['is_use' => 1, 'use_time' => time(), 'binding_time' => time(), 'use_partner_id' => $partner['id']]);
        });
        return CommonService::success([], '续费成功！');
    }


}
